#include <csugl.h>

#include <glad/glad.h>
#include <GLFW/glfw3.h>

#include <glog/logging.h>

int batch_test(int argc, char const *argv[]) {
    FLAGS_stderrthreshold = 0;
    google::InitGoogleLogging(argv[0]);

    auto app = csugl::singleton<csugl::Application>::getInstance();
    auto window = &app->GetWindow();
    window->Resize(600, 600);

    auto shader = csugl::MakeRef<csugl::Shader>("../assets/shader/gizmos.glsl");

    float triangle_vert[15] = {
        -0.0f,  0.0f,   0.3f,1.0f,0.2f,
        100.0f, 100.0f, 0.3f,0.3f,1.0f,
        0.0f,  100.0f,  1.0f,0.3f,0.4f,
    };
    unsigned int triangle_indi[3] = {
        0, 1, 2
    };

    float quad_vert[20] = {
        0.0f, 0.0f ,    0.3f,1.0f,0.2f,
        0.0f, 100.0f,   1.0f,0.3f,0.4f,
        100.0f, 0.0f,   0.5f,0.5f,0.5f,
        100.0f, 100.0f, 0.3f,0.3f,1.0f,
    };
    unsigned int quad_indi[6] = {
        3, 4, 5,
        5, 4, 6
    };

    bool draw_triangle = true;

    window->addEventCallback([&](csugl::Event &ev){
        csugl::EventDispatcher d(ev);
        d.Dispatch<csugl::KeyPressedEvent>([&](csugl::KeyPressedEvent &ev){
            if(ev.keyCode == csugl::Key::A){
                draw_triangle = !draw_triangle;
            }
            return false;
        });
    });

    auto vb = csugl::VertexBuffer::Create<float>(35);
    auto va_tri = csugl::VertexArray::Creat();
    auto va_quad = csugl::VertexArray::Creat();
    auto eb_tri = csugl::IndexBuffer::Create(3, triangle_indi);
    auto eb_quad = csugl::IndexBuffer::Create(3 * 2, quad_indi);
    
    va_tri->SetIndexBuffer(eb_tri);
    va_tri->AddVertexBuffer(vb, csugl::BufferLayout({
        {csugl::BufferElementType::Float2},
        {csugl::BufferElementType::Float3}
    }));
    vb->SetData(15, triangle_vert);
    eb_tri->Bind();
    
    va_quad->SetIndexBuffer(eb_quad);
    va_quad->AddVertexBuffer(vb, csugl::BufferLayout({
        {csugl::BufferElementType::Float2},
        {csugl::BufferElementType::Float3}
    }));
    vb->SetData(20, quad_vert);
    eb_quad->Bind();

    shader->Use();
    auto size = static_cast<glm::vec2>(window->GetSize());
    shader->SetVector2("_window_size", size);

    while(app->isOpen()){
        glClearColor(0.1f, 0.3f, 0.2f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        shader->Use();
        shader->SetVector2("_window_size", static_cast<glm::vec2>(window->GetSize()));

        if (draw_triangle) {
            va_tri->Bind();
            glDrawElements(GL_TRIANGLES, 3 * 1, GL_UNSIGNED_INT, (const void *)0);
        } else {
            va_quad->Bind();
            glDrawElements(GL_TRIANGLES, 3 * 2, GL_UNSIGNED_INT, (const void *)0);
        }

        window->Display();
    }

    csugl::singleton<csugl::Application>::destroy();

    return 0;
}